var db = require('../middleware/connection.js').db();
var crypt = require('../middleware/crypto.js');


 
function usernameExist(username,callback) {
	sql = "SELECT * FROM browsergame.user WHERE '"+username+"'=user.username";
	
	db.query(sql,function(err,rows) {
		 console.log(rows.length);
		 var rl = rows.length;
		 var result;
		 if (rl == 1) {
		 	result = true;
		 } else {
		 	result = false;
		 }
		 callback(result);
	} );
}


function register(username,password,req,res) {
	var minNumberofChars = 6;
    var maxNumberofChars = 16;
    var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
    if(password.length < minNumberofChars || password.length > maxNumberofChars){
		console.log('password should be min. 6 charecters long, and maximum 16 charecters long!')
        return false;
    }
    if(!regularExpression.test(password)) {
        console.log("password should contain atleast one number and one special character");
        return false;
    }

    
    crypt.encrypt(password,function(hash_password,hash_salt){
    	//db.connect();
    	console.log(hash_password.length+' | '+hash_salt.length);
		var sql = "INSERT INTO browsergame.user(`username`,`password`,`salt`) VALUES('"+username+"','"+hash_password+"','"+hash_salt+"')";
		//console.log(sql);
		db.query(sql,function(err,result) {
			req.session.uid = result.insertId;
			ii = result.insertId;
			sql = "INSERT INTO browsergame.user_buildings(`user_id`,`gold`) VALUES("+ii+","+1+")";
			db.query(sql,function(err,result) {
				sql = "INSERT INTO browsergame.user_res(`gold`,`user_id`) VALUES("+1+","+ii+")";
				db.query(sql,function(err,result) {});
			});
			res.redirect('/success');
		});
		//db.end();
		console.log('did it work.....?');
		
    });
	console.log('eh?!'); 

}


	



module.exports = function(app) {


	app.get('/login',function(req,res){
	console.log('Request from: '+req.ip);
	console.log('on tick: '+tick+' //');
	res.render('index.html');

	});


	app.get('/register',function(req,res){
	console.log('Request from: '+req.ip);
	console.log('on tick: '+tick+' //');
	res.render('register.html');

	});



	

	app.post('/auth',function(req,res) {
		u = req.body.usr;
		p = req.body.pwd;
		sql = "SELECT * from browsergame.user WHERE '"+u+"'=user.username";
		console.log(sql);
		db.query(sql, function(err,row) {
			if (err) { console.log(err); }
				else { 
					if (row.length == 1) {	
						var salt = row[0].salt;
						console.log('salt: '+ salt +'\n');
						crypt.checkEncrypt(p,salt,function(hash){
							 console.log('hash: '+hash +'\n');
							 console.log('db_hash: '+row[0].password +'\n' );
							 if (hash == row[0].password) {
							 	console.log('TRUE!');
							 }

						})
						
					} else {
						console.log('row is null!');
					}
				}
		}); 
	});

	// NB: ONLY WHEN POST
	app.post('/registrate',function(req,res) {
		usr = req.body.usr;
		pwd = req.body.pwd;

		usernameExist(usr,function(result) {
			if (!result) {
				if(register(usr,pwd,req,res) == false) {
					console.log('password does not meet requirements. //render register.ejs with fail msg');
				}
			} else {
				console.log('that username is already taken // render register.ejs with fail msg');
			}
		});

	});


}
